package net.maergaiyun.strategy;

import net.maergaiyun.enums.BizCodeEnum;
import net.maergaiyun.exception.BizException;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class CustomDBPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    /**
     * @param availableTargetNames 数据源集合
     *                             分库时值为所有分片库的集合 databaseNames
     *                             分表时为对应分片库中所有分片表的集合 tablesNames
     * @param preciseShardingValue 分片属性，包括
     *                             logicTableName 逻辑表
     *                             columnName 分片键（字段）
     *                             value 从SQL中解析出的分片键的值
     * @return
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> preciseShardingValue) {
        // 获取短链码第1位
        String codePrefix = preciseShardingValue.getValue().substring(0, 1);

        for (String targetName : availableTargetNames) {
            String targetNameSuffix = targetName.substring(targetName.length() - 1);
            if (codePrefix.equals(targetNameSuffix)) {
                return targetName;
            }
        }
        throw new BizException(BizCodeEnum.DB_ROUTE_NOT_FOUND);
    }
}
